import { defineEventHandler, getQuery, readBody } from 'h3';

import { usePageResponseSuccess, useResponseError } from '../../utils/response';

// 司机补贴统计分析数据生成
function generateSubsidyAnalyticsData(drivers: any[], subsidyConfigs: any[]) {
  const analyticsData = [];

  // 获取启用状态的补贴配置
  const enabledConfigs = subsidyConfigs.filter(
    (config) => config.status === '启用',
  );
  const inProvinceConfig = enabledConfigs.find(
    (config) => config.areaType === 'in',
  );
  const outProvinceConfig = enabledConfigs.find(
    (config) => config.areaType === 'out',
  );

  // 获取在职司机
  const activeDrivers = drivers.filter((driver) => driver.status === '在职');

  // 为每个在职司机生成3个月的数据（当前月、上月、上上月）
  const months = ['2024-01', '2024-02', '2024-03'];

  for (const month of months) {
    // 为每个月生成10名司机的数据
    for (let i = 0; i < 10; i++) {
      const driver = activeDrivers[i % activeDrivers.length];

      // 生成随机的公里数
      const inProvinceKm = Math.round(Math.random() * 2000 + 500); // 省内公里数：500-2500
      const outProvinceKm = Math.round(Math.random() * 1500 + 300); // 省外公里数：300-1800

      // 计算总补贴
      const totalSubsidy =
        Math.round(
          (inProvinceKm * (inProvinceConfig?.subsidyAmount || 2.5) +
            outProvinceKm * (outProvinceConfig?.subsidyAmount || 3)) *
            100,
        ) / 100;

      // 生成随机的更新时间
      const updateTime = `${month}-15 ${Math.floor(Math.random() * 24)
        .toString()
        .padStart(2, '0')}:${Math.floor(Math.random() * 60)
        .toString()
        .padStart(2, '0')}:00`;

      analyticsData.push({
        driverId: driver.driverId,
        fullName: driver.fullName,
        phoneNumber: driver.phoneNumber,
        inProvinceKm,
        outProvinceKm,
        inProvinceStandard: inProvinceConfig?.subsidyAmount || 2.5,
        outProvinceStandard: outProvinceConfig?.subsidyAmount || 3,
        totalSubsidy,
        updateTime,
      });
    }
  }

  return analyticsData;
}

// 由于我们无法直接导入其他模块的数据，这里我们模拟数据
const mockDrivers = [
  {
    driverId: 10_001,
    fullName: '张三',
    phoneNumber: '13800138001',
    status: '在职',
  },
  {
    driverId: 10_002,
    fullName: '李四',
    phoneNumber: '13800138002',
    status: '在职',
  },
  {
    driverId: 10_003,
    fullName: '王五',
    phoneNumber: '13800138003',
    status: '在职',
  },
  {
    driverId: 10_004,
    fullName: '赵六',
    phoneNumber: '13800138004',
    status: '在职',
  },
  {
    driverId: 10_005,
    fullName: '孙七',
    phoneNumber: '13800138005',
    status: '在职',
  },
  {
    driverId: 10_006,
    fullName: '周八',
    phoneNumber: '13800138006',
    status: '在职',
  },
  {
    driverId: 10_007,
    fullName: '吴九',
    phoneNumber: '13800138007',
    status: '在职',
  },
  {
    driverId: 10_008,
    fullName: '郑一',
    phoneNumber: '13800138008',
    status: '在职',
  },
  {
    driverId: 10_009,
    fullName: '王二',
    phoneNumber: '13800138009',
    status: '在职',
  },
  {
    driverId: 10_010,
    fullName: '陈三',
    phoneNumber: '13800138010',
    status: '在职',
  },
];

const mockSubsidyConfigs = [
  { areaType: 'in', subsidyAmount: 2.5, status: '启用' },
  { areaType: 'out', subsidyAmount: 3, status: '启用' },
];

// 生成补贴统计分析数据
const subsidyAnalyticsData = generateSubsidyAnalyticsData(
  mockDrivers,
  mockSubsidyConfigs,
);

// 获取补贴统计分析数据
export const getSubsidyAnalyticsHandler = defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const page = Number.parseInt(query.page as string) || 1;
    const pageSize = Number.parseInt(query.pageSize as string) || 20;
    const month = query.month as string; // 筛选月份

    // 筛选数据
    let filteredData = subsidyAnalyticsData;

    if (month) {
      filteredData = filteredData.filter((item) =>
        item.updateTime.startsWith(month),
      );
    }

    // 分页处理
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);

    return usePageResponseSuccess(page, pageSize, paginatedData, {
      message: '获取成功',
    });
  } catch {
    return useResponseError('获取失败');
  }
});

// 导出补贴统计分析数据
export const exportSubsidyAnalyticsHandler = defineEventHandler(
  async (event) => {
    try {
      const body = await readBody(event);
      const month = body.month;

      // 筛选数据用于导出
      let filteredData = subsidyAnalyticsData;

      if (month) {
        filteredData = filteredData.filter((item) =>
          item.updateTime.startsWith(month),
        );
      }

      // 模拟导出延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      return useResponseSuccess({
        downloadUrl: '/api/dashboard/subsidyAnalytics/export/download',
        fileName: `司机补贴统计_${month || 'all'}.xlsx`,
      });
    } catch {
      return useResponseError('导出失败');
    }
  },
);
